// 账号处理程序
export const handleAccounts = {
  // 获取账号列表
  async list(request, env) {
    const { user } = request;
    
    // 从数据库获取账号列表
    const accounts = await env.DB.prepare(`
      SELECT a.* 
      FROM accounts a
      JOIN employees e ON a.employee_id = e.id
      WHERE e.phone = ? OR e.email = ?
    `).bind(user.value, user.value).all();
    
    return new Response(JSON.stringify({
      code: 200,
      data: {
        accounts: accounts.map(account => ({
          id: account.id,
          name: account.name,
          type: account.type
        }))
      }
    }));
  },

  // 绑定账号
  async bind(request, env) {
    const { user } = request;
    const { appId, accountId } = await request.json();
    
    // 验证账号所有权
    const account = await env.DB.prepare(`
      SELECT a.* 
      FROM accounts a
      JOIN employees e ON a.employee_id = e.id
      WHERE a.id = ? AND (e.phone = ? OR e.email = ?)
    `).bind(accountId, user.value, user.value).first();
    
    if (!account) {
      return new Response(JSON.stringify({
        code: 403,
        message: '无权绑定该账号'
      }));
    }
    
    // 创建绑定关系
    await env.DB.prepare(`
      INSERT INTO account_app_bindings (account_id, app_id)
      VALUES (?, ?)
      ON CONFLICT (account_id, app_id) DO NOTHING
    `).bind(accountId, appId).run();
    
    return new Response(JSON.stringify({
      code: 200,
      message: '绑定成功'
    }));
  }
};
